package com.example.firstdemo.network.service

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.example.firstdemo.network.api.user.Gender
import com.example.firstdemo.network.api.user.UserInfo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

// DataStore 键定义
object PreferencesKeys {
    val TOKEN = stringPreferencesKey("auth_token")
    val USER_ID = longPreferencesKey("user_id")
    val USER_NAME = stringPreferencesKey("user_name")
    val NICK_NAME = stringPreferencesKey("nick_name")
    val AVATAR = stringPreferencesKey("avatar")
    val DEPT_ID = longPreferencesKey("dept_id")
    val GENDER = stringPreferencesKey("gender")
    val PHONE_NUMBER = stringPreferencesKey("phone_number")
    val EMAIL = stringPreferencesKey("email")
    val IS_LOGGED_IN = booleanPreferencesKey("is_logged_in")
}

// 扩展属性，创建 DataStore
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "app_prefs")

// User 管理器
object UserManager {
    private lateinit var dataStore: DataStore<Preferences>

    private val _currentToken = MutableStateFlow<String?>(null)
    val currentToken: StateFlow<String?> = _currentToken.asStateFlow()

    private val _currentUser = MutableStateFlow<UserInfo?>(null)
    val currentUser: StateFlow<UserInfo?> = _currentUser.asStateFlow()

    private val _isLoggedIn = MutableStateFlow<Boolean>(false)
    val isLoggedIn = _isLoggedIn.asStateFlow()

    // 初始化
    fun init(context: Context) {
        dataStore = context.dataStore
        // 从 DataStore 读取数据
        CoroutineScope(Dispatchers.IO).launch {
            loadInitialData()
            currentToken.collect { token ->
                _isLoggedIn.value = token != null
            }
        }
    }

    private suspend fun loadInitialData() {
        val preferences = dataStore.data.first()
        _currentToken.value = preferences[PreferencesKeys.TOKEN]

        val userId = preferences[PreferencesKeys.USER_ID]
        val userName = preferences[PreferencesKeys.USER_NAME]
        val nickName = preferences[PreferencesKeys.NICK_NAME]
        val avatar = preferences[PreferencesKeys.AVATAR]
        val deptId = preferences[PreferencesKeys.DEPT_ID]
        val gender = preferences[PreferencesKeys.GENDER]
        val phoneNumber = preferences[PreferencesKeys.PHONE_NUMBER]
        val email = preferences[PreferencesKeys.EMAIL]
        _currentUser.value = UserInfo(
            userId = userId ?: 0,
            userName = userName ?: "",
            nickName = nickName ?: "",
            avatar = avatar ?: "",
            deptId = deptId ?: 0,
            gender = when (gender) {
                "0" -> Gender.MALE
                "1" -> Gender.FEMALE
                else -> Gender.UNKNOWN
            },
            phoneNumber = phoneNumber ?: "",
            email = email ?: ""
        )
    }

    // 保存 token
    suspend fun saveToken(token: String) {
        _currentToken.value = token
        dataStore.edit { preferences ->
            preferences[PreferencesKeys.TOKEN] = token
        }
    }

    // 保存用户信息
    suspend fun saveUserInfo(userInfo: UserInfo) {
        _currentUser.value = userInfo
        dataStore.edit { preferences ->
            preferences[PreferencesKeys.USER_ID] = userInfo.userId
            preferences[PreferencesKeys.USER_NAME] = userInfo.userName
            preferences[PreferencesKeys.NICK_NAME] = userInfo.nickName
            preferences[PreferencesKeys.AVATAR] = userInfo.avatar
            preferences[PreferencesKeys.DEPT_ID] = userInfo.deptId
            preferences[PreferencesKeys.GENDER] = when (userInfo.gender) {
                Gender.MALE -> "0"
                Gender.FEMALE -> "1"
                else -> "2"
            }
            preferences[PreferencesKeys.PHONE_NUMBER] = userInfo.phoneNumber
            preferences[PreferencesKeys.EMAIL] = userInfo.email
            preferences[PreferencesKeys.IS_LOGGED_IN] = true
        }
    }

    // 清除登录信息
    suspend fun clear() {
        _currentToken.value = null
        _currentUser.value = null
        dataStore.edit { preferences ->
            preferences.remove(PreferencesKeys.TOKEN)
            preferences.remove(PreferencesKeys.USER_ID)
            preferences.remove(PreferencesKeys.USER_NAME)
            preferences.remove(PreferencesKeys.NICK_NAME)
            preferences.remove(PreferencesKeys.AVATAR)
            preferences.remove(PreferencesKeys.DEPT_ID)
            preferences.remove(PreferencesKeys.GENDER)
            preferences.remove(PreferencesKeys.PHONE_NUMBER)
            preferences.remove(PreferencesKeys.EMAIL)
            preferences.remove(PreferencesKeys.IS_LOGGED_IN)
        }
    }
}